function [ dataVals, downSampleFlag ] = downsampleData( dataVals, downThreshold, downSampleFlag )
% Attempts to downsample ECG to as close as possible to 128

dataLength = length(dataVals);
i = 1;

while (dataLength / (i + 1)) > downThreshold
    i = i + 1;
end

dataVals = downsample(dataVals, i);

zerosToRemove = length(dataVals) - downThreshold;

posVals = dataVals(dataVals(:, 2) ~= 0, :);

zeroVals = dataVals(dataVals(:, 2) == 0, :);

% Verifies that there are sufficient zero values to remove in order to
% reach the 128 points necessary for downstream analysis without loss of
% fidelity
if zerosToRemove > length(zeroVals(:, 1))
    
    downSampleFlag = 1;
    
    return
    
end

zeroValsMidPt = round(length(zeroVals) / 2);

upper = zeroValsMidPt + floor((zerosToRemove / 2));
 
lower = zeroValsMidPt - floor((zerosToRemove / 2));

switch mod(zerosToRemove, 2)
    
    case 0
        
        zeroVals(lower:upper - 1, :) = [];
        
    case 1
        
        zeroVals(lower:upper, :) = [];
     
end
    
dataVals = vertcat(posVals, zeroVals);


end

